//
//  Utils.m
//  Audian
//
//  Created by BXChinh on 12/25/13.
//  Copyright (c) 2013 Vũ Văn Long. All rights reserved.
//

#import "Utils.h"
#import "Reachability.h"
#import "PDKeychainBindings.h"
#define NETWORK_ERROR   @"An error occurred.We do not detect an Internet connection. Please check your network connection and try again!"
static NSInteger nsIType;
static int isTypeScreen =0;
static BOOL isMainScreen =true;
static NSString *ISO=@"";
static NSString *LOADZONE=@"";
@implementation Utils

+(void)SetISO:(NSString *)iso andLoadZone:(NSString *)loadzone
{
    ISO=iso;
    LOADZONE=loadzone;
}
+(NSString *)getISO
{
    return ISO;
}
+(NSString *)getLoadZone
{
    return LOADZONE;
}
+(int)getTypeScreen
{
    return isTypeScreen;
}
+(void)setTypeScreen:(int)value
{
    isTypeScreen=value;
}
+ (NSString *)uniqueVendor {
    
    PDKeychainBindings *keychain = [PDKeychainBindings sharedKeychainBindings];
    NSString *uniqueIdentifier = [keychain objectForKey:kKeyVendor];
    
    if (!uniqueIdentifier || !uniqueIdentifier.length) {
        
        NSUUID *udid = [[UIDevice currentDevice] identifierForVendor];
        uniqueIdentifier = [udid UUIDString];
        [keychain setObject:uniqueIdentifier forKey:kKeyVendor];
    }
    
    return uniqueIdentifier;
}

+(BOOL)getMainScreen
{
    return isMainScreen;
}
+(void)setMainScreen:(BOOL)value
{
    isMainScreen=value;
}


+(NSInteger)getCurrentType
{
    return nsIType;
}
+(void)setCurrentType:(int)type
{
    nsIType= type;
}

+(void) showAlertViewWithTitle:(NSString*)aTitle withMessage:(NSString*)aMessage {
	UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:aTitle
														message:aMessage
													   delegate:nil
											  cancelButtonTitle:@"OK"
											  otherButtonTitles:nil];
	[alertView show];
}

+(void) showAlertViewWithTitle:(NSString*)aTitle withMessage:(NSString*)aMessage andTag:(NSInteger)tag andDelegate :(id)delegate{
	UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:aTitle
														message:aMessage
													   delegate:nil
											  cancelButtonTitle:@"OK"
											  otherButtonTitles:nil];
    [alertView setTag:tag];
    [alertView setDelegate:delegate];
	[alertView show];
}


+(BOOL)checkNetworkWithPopUp{
    BOOL result = YES;
    NetworkStatus remoteHostStatus = [[Reachability reachabilityForInternetConnection] currentReachabilityStatus];
    if(remoteHostStatus == NotReachable) {
        result = NO;
    }
    
    if(!result){
        [Utils showAlertViewWithTitle:@"" withMessage:NETWORK_ERROR];
    }
    return result;
}

+ (BOOL)checkNetwork{
    BOOL result = YES;
    NetworkStatus remoteHostStatus = [[Reachability reachabilityForInternetConnection] currentReachabilityStatus];
    if(remoteHostStatus == NotReachable) {
        result = NO;
    }
    
    return result;
}

+ (id)objectForKeyNotNull:(id)key andDictionnary:(NSDictionary*)dic{
    
    id object = [dic objectForKey:key];
    if (object == [NSNull null])
        return nil;
    
    return object;
}

+ (int)dayLeftFromNow:(NSDate*)aDate{
    NSDate *now = [Utils getDateTimeAtZeroTimeWithDate:[NSDate date]] ;

    NSCalendar *gregorianCalendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
    
    NSDateComponents *components = [gregorianCalendar components:NSDayCalendarUnit fromDate:now toDate:aDate options:0];
    NSLog(@"Ex %@ andNow %@",aDate,now);
    return (int)[components day];
}

/*
 @StrDate : yyyy-MM-dd'T'HH:mm:ss
 */
//    NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
//    NSDateComponents *components = [calendar components:NSYearCalendarUnit|NSMonthCalendarUnit|NSDayCalendarUnit|NSHourCalendarUnit|NSMinuteCalendarUnit|NSSecondCalendarUnit fromDate:[Utils getDateFromString:strDate]];
//    //[components setHour:0];
//    //[components setMinute:0];
//    //[components setSecond:0];
//    NSDate *dateResult = [calendar dateFromComponents:components];
+ (NSDate*)getDateTimeAtZeroTime:(NSString *)strDate {

    NSDateFormatter* _twitter_dateFormatter = [[NSDateFormatter alloc] init];
    [_twitter_dateFormatter setFormatterBehavior:NSDateFormatterBehaviorDefault];
    [_twitter_dateFormatter setDateFormat:@"yyyy-MM-dd'T'HH:mm:ss.SSSZ"];
    [_twitter_dateFormatter setTimeZone:[NSTimeZone localTimeZone]];
    NSDate *dateResult = [_twitter_dateFormatter dateFromString:strDate];
    if(dateResult==nil)
    {
        [_twitter_dateFormatter setDateFormat:@"yyyy-MM-dd'T'HH:mm:ssZZZ"];
    }
    dateResult = [_twitter_dateFormatter dateFromString:strDate];
    NSDateFormatter* df_utc = [[NSDateFormatter alloc] init];
    [df_utc setTimeZone:[NSTimeZone timeZoneWithName:@"ICT"]];
    [df_utc setDateFormat:@"yyyy.MM.dd G 'at' HH:mm:ss zzz"];
    
    NSDateFormatter* df_local = [[NSDateFormatter alloc] init];
    [df_local setTimeZone:[NSTimeZone timeZoneWithName:@"EST"]];
    [df_local setDateFormat:@"yyyy.MM.dd G 'at' HH:mm:ss zzz"];
    //NSString* ts_utc_string = [df_utc stringFromDate:dateResult];
    NSString* ts_local_string = [df_local stringFromDate:dateResult];
    //NSLog(@"server time :%@ -- local time: %@",ts_utc_string,ts_local_string);
    return  [df_local dateFromString:ts_local_string];//dateResult;
}

+ (NSDate*)getDateTimeAtZeroTimeWithDate:(NSDate *)date {
    NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
    NSDateComponents *components = [calendar components:NSYearCalendarUnit|NSMonthCalendarUnit|NSDayCalendarUnit fromDate:date];
    [components setHour:0];
    [components setMinute:0];
    [components setSecond:0];
    NSDate *dateResult = [calendar dateFromComponents:components];

    return dateResult;
}

+ (NSString*)timeStringLeftFromNow:(NSDate*)aDate{
    NSDate *now = [NSDate date];
    
    NSCalendar *gregorianCalendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
    
    NSDateComponents *components = [gregorianCalendar components:NSDayCalendarUnit|NSCalendarUnitHour|NSCalendarUnitMinute fromDate:now toDate:aDate options:0];
    
    NSMutableString *strResult = [NSMutableString string];
    if([components day]){
        NSString *dayStr = [components day] != 1 ?
        [NSString stringWithFormat:@"%d days ",[components day]] :
        [NSString stringWithFormat:@"%d day ",[components day]];
        
        [strResult appendString:dayStr];
        
    }
    
    if([components hour]){
        NSString *dayStr = [components hour] != 1 ?
        [NSString stringWithFormat:@"%d hours ",[components hour]] :
        [NSString stringWithFormat:@"%d hour ",[components hour]];
        
        [strResult appendString:dayStr];

    }

    if([components minute]){
        NSString *dayStr = [components minute] != 1 ?
        [NSString stringWithFormat:@"%d mins ",[components minute]] :
        [NSString stringWithFormat:@"%d min ",[components minute]];
        
        [strResult appendString:dayStr];

    }

    [strResult appendString:@" left"];
   
    return strResult;
}

+ (NSDate *)getDateFromString:(NSString *)dateString
{
    if (dateString == nil || [dateString isEqual:[NSNull null]]) {
        return nil;
    }
    NSDateFormatter *rfc3339TimestampFormatterWithTimeZone = [[NSDateFormatter alloc] init];
    [rfc3339TimestampFormatterWithTimeZone setLocale:[[NSLocale alloc] initWithLocaleIdentifier:@"en_US_POSIX"]];
    [rfc3339TimestampFormatterWithTimeZone setDateFormat:@"yyyy-MM-dd'T'HH:mm:ss"];
    
    NSDate *theDate = nil;
    NSError *error = nil;
    if (![rfc3339TimestampFormatterWithTimeZone getObjectValue:&theDate forString:dateString range:nil error:&error]) {
        NSLog(@"Date '%@' could not be parsed: %@", dateString, error);
    }
    
    return theDate;
}

+(NSString*)stringFromDate:(NSDate*)date withFormat:(NSString*)format{
    NSDateFormatter *formatter;
    NSString        *dateString;
    
    formatter = [[NSDateFormatter alloc] init];
    [formatter setDateFormat:format];
    
    dateString = [formatter stringFromDate:date];
    return dateString;
}

+ (BOOL) validateEmail: (NSString *) candidate {
    NSString *emailRegex =
    @"(?:[a-z0-9!#$%\\&'*+/=?\\^_`{|}~-]+(?:\\.[a-z0-9!#$%\\&'*+/=?\\^_`{|}"
    @"~-]+)*|\"(?:[\\x01-\\x08\\x0b\\x0c\\x0e-\\x1f\\x21\\x23-\\x5b\\x5d-\\"
    @"x7f]|\\\\[\\x01-\\x09\\x0b\\x0c\\x0e-\\x7f])*\")@(?:(?:[a-z0-9](?:[a-"
    @"z0-9-]*[a-z0-9])?\\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?|\\[(?:(?:25[0-5"
    @"]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-"
    @"9][0-9]?|[a-z0-9-]*[a-z0-9]:(?:[\\x01-\\x08\\x0b\\x0c\\x0e-\\x1f\\x21"
    @"-\\x5a\\x53-\\x7f]|\\\\[\\x01-\\x09\\x0b\\x0c\\x0e-\\x7f])+)\\])";
    NSPredicate *emailTest = [NSPredicate predicateWithFormat:@"SELF MATCHES[c] %@", emailRegex];
    
    return [emailTest evaluateWithObject:candidate];
}
+ (NSDate *)serverTimeToDeviceTime:(NSDate*)aDate{
    
    //NSLog(@"IIIII %@",aDate);
    return aDate;
    
//    NSDate* ts_utc = aDate;
//    
//    NSDateFormatter* df_utc = [[NSDateFormatter alloc] init];
//    [df_utc setTimeZone:[NSTimeZone timeZoneWithName:@"ICT"]];
//    [df_utc setDateFormat:@"yyyy.MM.dd G 'at' HH:mm:ss zzz"];
//    
//    NSDateFormatter* df_local = [[NSDateFormatter alloc] init];
//    [df_local setTimeZone:[NSTimeZone timeZoneWithName:@"EST"]];
//    [df_local setDateFormat:@"yyyy.MM.dd G 'at' HH:mm:ss zzz"];
//    
//    NSString* ts_utc_string = [df_utc stringFromDate:ts_utc];
//    NSString* ts_local_string = [df_local stringFromDate:ts_utc];
//    NSLog(@" AAAAAAA Input %@ - server time :%@ -- local time: %@",aDate,ts_utc_string,ts_local_string);
//    
//   return [df_local dateFromString:ts_local_string];
}
+(NSDate*)getDateYesterday
{
    //NSDate *yesterday =[NSDate dateWithTimeIntervalSinceNow:-24*60*60];
    
        NSDate* ts_utc = [NSDate date];
        
        NSDateFormatter* df_utc = [[NSDateFormatter alloc] init];
        [df_utc setTimeZone:[NSTimeZone timeZoneWithName:@"ICT"]];
        [df_utc setDateFormat:@"yyyy.MM.dd G 'at' HH:mm:ss zzz"];
        
        NSDateFormatter* df_local = [[NSDateFormatter alloc] init];
        [df_local setTimeZone:[NSTimeZone timeZoneWithName:@"EST"]];
        [df_local setDateFormat:@"yyyy.MM.dd G 'at' HH:mm:ss zzz"];
        
        NSString* ts_utc_string = [df_utc stringFromDate:ts_utc];
        NSString* ts_local_string = [df_local stringFromDate:ts_utc];
        //NSLog(@"=======> NSdate %@ ------BBB--------^^",[NSDate date] );
       // NSLog(@"Input %@ - server time :%@ -- local time: %@",ts_utc,ts_utc_string,ts_local_string);


    return [df_local dateFromString:ts_local_string];
}

@end
